package com.hydra.jres.handler;

import com.hydra.base.error.BusinessException;
import com.hydra.base.resp.ResultError;
import com.hydra.base.utils.JsonUtil;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * Feign的错误处理器
 * @Author Hydra
 * @Date 2022/5/16 10:53
 */
@Slf4j
@Component
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            InputStream is = response.body().asInputStream();
            String result = IOUtils.toString(is, StandardCharsets.UTF_8);
            log.error("请求方法：{}, 请求结果：{}", methodKey, result);
            String errorMessage = result;
            if(result.startsWith("{")){
                ResultError error = JsonUtil.parseObject(result, ResultError.class);
                String message = error.getMessage();
                if(StringUtils.isBlank(message)){
                    message = error.getError();
                }
                if(StringUtils.isBlank(message)){
                    message = result;
                }
                errorMessage = message;
            }
            return new BusinessException(errorMessage);
        } catch (IOException e) {
            log.error("读取Feign结果IO流出错", e);
            return e;
        }
    }
}
